using Microsoft.Extensions.Caching.Distributed;
using net_work.Common;
using net_work.Common.Request;
using net_work.Data.Enum.System;
using net_work.Service.BackgroundTask.Handler;

namespace net_work.Service.BackgroundTask;

public class TaskProcessor(ITaskQueue taskQueue, TaskHandlerFactory taskHandlerFactory, IDistributedCache cache)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var taskRequest = await taskQueue.DequeueAsync(stoppingToken);

            if (taskRequest == null)
            {
                continue;
            }

            try
            {
                // 获取任务处理器并处理任务
                var taskHandler = taskHandlerFactory.GetTaskHandler(taskRequest.TaskType);
                await taskHandler.HandleAsync(taskRequest);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error occurred while processing task: {taskRequest.TaskId}, Error: {e.Message}");
            }
            finally
            {
                var isValue = taskRequest.Parameters.TryGetValue(TaskParams.FilePath, out var filePath);
                if (isValue && filePath != null)
                {
                    var filePathValue = (string)filePath;
                    // 确保文件在任务处理完成后被删除
                    if (!string.IsNullOrEmpty(filePathValue) && File.Exists(filePathValue))
                    {
                        try
                        {
                            // 删除文件
                            File.Delete(filePathValue);
                        }
                        catch (Exception deleteException)
                        {
                            Console.WriteLine(
                                $"Error occurred while deleting file: {filePathValue}, Error: {deleteException.Message}");
                        }
                    }
                }
            }
        }
    }
}